//
//  GlobalMethod+Function.m
//  MexicoLoan
//
//  Created by WXP on 2025/2/24.
//

#import "GlobalMethod+Function.h"
#import "WXPAuthCompleteView.h"

@implementation GlobalMethod (Function)

#pragma mark - 认证
+ (void)jumpToAuthWithAuthInfo:(NSString *)authInfo{
    // 通知首页 - 认证步骤改变
    NSDictionary *userInfo = @{@"auth_type": authInfo};
    [[NSNotificationCenter defaultCenter] postNotificationName:LOCAL_AUTH_INFO_SETP object:nil userInfo:userInfo];
#if DEBUG
      // 测试
//    [Global_Nav pushVCName:@"WXPAuthKTPVC" animated:true];
//    return;
#endif
    if([authInfo isEqualToString:KEY_CREDIT_INFO]){
        // 问卷
        [Global_Nav pushVCName:@"WXPAuthQuestionVC" animated:true];
    }else if([authInfo isEqualToString:KEY_IDENTITY_INFO]){
        // KTP
        [Global_Nav pushVCName:@"WXPAuthKTPVC" animated:true];
    }else if([authInfo isEqualToString:KEY_LIVENESS_INFO]){
        // 活体
        [Global_Nav pushVCName:@"WXPAuthFaceVC" animated:true];
    }else if([authInfo isEqualToString:KEY_PERSONAL_INFO]){
        // 个人信息
        [Global_Nav pushVCName:@"WXPAuthPersonalVC" animated:true];
    }else if([authInfo isEqualToString:KEY_INCOME_INFO]){
        // 收入信息
        [Global_Nav pushVCName:@"WXPAuthIncomeVC" animated:true];
    }else if([authInfo isEqualToString:KEY_CONTACT_INFO]){
        // 联系人
        [Global_Nav pushVCName:@"WXPAuthContactVC" animated:true];
    }else if([authInfo isEqualToString:KEY_BANK_INFO]){
        // 银行卡
        [Global_Nav pushVCName:@"WXPAuthBankCardVC" animated:true];
    }else if ([authInfo isEqualToString:@"AUTH_SUCCESS"]){
        // 认证成功 - 显示认证完成弹窗
        WXPAuthCompleteView * view = [WXPAuthCompleteView new];
        UIWindow * window = [UIApplication sharedApplication].windows.firstObject;
        [window endEditing:true];
        [window addSubview:view];
    }
}

#pragma mark - 按顺序取出每个认证步骤奖励的金钱
+ (NSArray *)getMoneyAuthStep:(NSDictionary *)response{
    NSArray * aryKeys = @[
        @"CREDIT_INFO",
        @"IDENTITY_INFO",
        @"LIVENESS_INFO",
        @"PERSONAL_INFO",
        @"INCOME_INFO",
        @"CONTACT_INFO",
        @"BANK_INFO",
    ];
    // 按照指定的顺序获取值
    NSMutableArray * arrayResult = [NSMutableArray array];
    for (NSString * key in aryKeys) {
        id value = response[key];
        if (value) {
            ModelBtn * model = [ModelBtn new];
            model.title = key;
            model.content = value;
            [arrayResult addObject:model];
        }
    }
    return arrayResult;
}

#pragma mark - 风控埋点
+ (void)addRiskControlWithType:(NSString *)type startTime:(NSString *)startTime endTime:(NSString *)endTime{
    [RequestApi requestAddRiskControlTrackingWithType:type startTime:startTime endTime:endTime delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}



#pragma mark - 显示金额
+ (NSString *)showMoney:(NSString *)moneyStr{
    moneyStr = [moneyStr stringByReplacingOccurrencesOfString:@"$" withString:@""];
    moneyStr = [moneyStr stringByReplacingOccurrencesOfString:@"," withString:@""];
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    formatter.maximumFractionDigits = 2;
    NSArray *components = [moneyStr componentsSeparatedByString:@"."];
    NSString *decimalPart = components.count > 1 ? components.lastObject : nil;
    if (decimalPart && [decimalPart isEqualToString:@"00"]) {
        // 小数部分是00，设置为整数
        formatter.minimumFractionDigits = 0;
        formatter.maximumFractionDigits = 0;
    } else if (decimalPart) {
        // 如果有小数部分但不是00，保留两位小数
        formatter.minimumFractionDigits = 2;
    } else {
        // 没有小数部分，直接显示整数
        formatter.minimumFractionDigits = 0;
        formatter.maximumFractionDigits = 0;
    }
    NSNumber *number = @([moneyStr doubleValue]);
    NSString *formattedString = [formatter stringFromNumber:number];
    return formattedString;
}

#pragma mark - double 转 string
+ (NSString *)showDoubleToStr:(double)number{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    formatter.minimumFractionDigits = 0;
    formatter.maximumFractionDigits = 2;
    NSString *formattedNumber = [formatter stringFromNumber:@(number)];
    return formattedNumber;
}


#pragma mark - 提示
+ (void)showAlert:(NSString *)strAlert{
    UIWindow * window = [WindowManager sharedManager].getCurrentWindow;
    [window endEditing:true];
    [[GlobalData sharedInstance].Global_NoticeView showNotice:strAlert time:1 frame:[UIScreen mainScreen].bounds viewShow:window];
}

#pragma mark - 收键盘
+ (void)endEditing{
    UIWindow * window = [UIApplication sharedApplication].windows.firstObject;
    [window endEditing:true];
}



#pragma mark - 判断是不是接口：登录/验证码/保存认证信息/修改银行卡，这几个接口code为500也要弹窗提醒返回的message
+ (BOOL)checkWhetherShowMessageWithUrl:(NSString *)url{
    NSRange loginRange = [url rangeOfString:@"USER_ANTIFRAUDLOGINSMS"];
    NSRange sendSmsCountRange = [url rangeOfString:SEND_SMS_COUNT];
    NSRange sendSmsRange = [url rangeOfString:SEND_SMS_MAPPING];
    NSRange saveUserInfoRange = [url rangeOfString:@"AUTH_SAVEUSERINFO"];
    NSRange modifyBankCardRange = [url rangeOfString:@"AUTH_MODIFYBANKCARD"];
    if (loginRange.location != NSNotFound ||
        sendSmsCountRange.location != NSNotFound ||
        sendSmsRange.location != NSNotFound ||
        saveUserInfoRange.location != NSNotFound ||
        modifyBankCardRange.location != NSNotFound) {
        // 是登录/验证码/保存认证信息/修改银行卡接口
        return true;
    }else{
        return false;
    }
}

#pragma mark - 异步执行
+ (void)asynthicBlock:(void (^)(void))block{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block);
}
+ (void)mainQueueBlock:(void (^)(void))block{
    dispatch_async(dispatch_get_main_queue(), block);
}

#pragma mark - 获取当前时间戳
+ (NSString *)getTimeStamp{
    return [NSString stringWithFormat:@"%.f",[[NSDate date] timeIntervalSince1970]];
}

+ (NSString *)getTimeStampMillisecond{
    return [NSString stringWithFormat:@"%.f",[[NSDate date] timeIntervalSince1970]*1000];
}

#pragma mark - 压缩图片
+ (NSData *)compressImage:(UIImage *)image toMaxSize:(NSUInteger)maxSizeKB {
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0); // 初始以最高质量压缩
    NSUInteger imageSizeKB = imageData.length / 1024; // 获取图像大小（KB）
    if (imageSizeKB <= maxSizeKB) {
        // 如果图像已经小于目标大小，则直接返回
        return imageData;
    }
    // 设置压缩质量的初始值
    CGFloat compressionQuality = 1.0;
    CGFloat maxCompressionQuality = 0.1; // 最低质量（如果达到该质量，停止压缩）
    while (imageSizeKB > maxSizeKB && compressionQuality > maxCompressionQuality) {
        // 每次降低压缩质量，逐步压缩
        compressionQuality -= 0.1; // 每次减少 10% 的压缩质量
        imageData = UIImageJPEGRepresentation(image, compressionQuality);
        imageSizeKB = imageData.length / 1024;
    }
    // 如果压缩质量过低，仍然超过目标大小，可以进一步调整尺寸
    if (imageSizeKB > maxSizeKB) {
        // Resize image to reduce the size further if needed
        CGSize newSize = CGSizeMake(image.size.width * 0.8, image.size.height * 0.8); // 80% original size
        UIGraphicsBeginImageContextWithOptions(newSize, NO, 1.0);
        [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
        UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        imageData = UIImageJPEGRepresentation(resizedImage, compressionQuality);
    }
    return imageData;
}

#pragma mark - 校验邮箱格式
+ (BOOL)isValidEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

#pragma mark - 某一动作一天只执行一次
+ (void)executeOncePerDayWithKey:(NSString *)key block:(void (^)(void))block{
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd";
    NSString *todayString = [dateFormatter stringFromDate:today];
    NSString *lastExecutionDate = [GlobalMethod readStrFromUserDefaults:key];
    // 如果上次执行日期为空或者不是今天，则执行方法
    if (![lastExecutionDate isEqualToString:todayString]) {
        // 执行方法
        block();
        // 更新上次执行的日期为今天
        [GlobalMethod writeStr:todayString forKey:key];
    }
}

#pragma mark - 打点
+ (void)hitPointWithPageName:(NSString *)pageName action:(NSString *)action extInfo:(NSDictionary * _Nullable)extInfo{
    NSString * extInfoStr = @"";
    if(extInfo){
        extInfoStr = [GlobalMethod exchangeDicToJson:extInfo];
    }
    [RequestApi requestHitPointWithPageName:pageName action:action extInfo:extInfoStr delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
            
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
            
    }];
}

+ (void)addADJEventWithToken:(NSString *)token phone:(NSString *)phone userId:(NSString *)userId{
//    ADJEvent * event = [[ADJEvent alloc] initWithEventToken:token];
//    [event addCallbackParameter:@"eventKey" value:@""];
//    [event addCallbackParameter:@"phone" value:UnPackStr(phone)];
//    [event addCallbackParameter:@"userId" value:UnPackStr(userId)];
//    [Adjust trackEvent:event];
}

#pragma mark - 用户详细行为埋点
+ (void)buryPointWithPageName:(NSString *)pageName featureName:(NSString *)featureName action:(NSString *)action type:(NSString *)type{
    [RequestApi requestBuryPointWithPageName:pageName featureName:featureName type:type action:action delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}


@end
